package com.fc.campusapplicationsystem.controller;

import com.fc.campusapplicationsystem.model.Asset;
import com.fc.campusapplicationsystem.service.AssetService;
import com.fc.campusapplicationsystem.util.ResponseOBJ;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:27
 */
@RestController
@RequestMapping("/assetController")
public class AssetController {
    @Autowired
    AssetService assetService;

    @GetMapping("/add")
    public ResponseOBJ<Integer> add(@RequestBody Asset asset) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = assetService.add(asset);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @GetMapping("/delete")
    public ResponseOBJ<Integer> delete(@RequestParam("assetId") Integer id) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = assetService.delete(id);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @GetMapping("/list")
    public ResponseOBJ<List<Asset>> list(@RequestParam("page") Integer page,
                                         @RequestParam("limit") Integer limit,
                                         @RequestParam(value = "key", required = false) String key) {
        ResponseOBJ<List<Asset>> responseOBJ = ResponseOBJ.getInstance();
        try {
            PageHelper.startPage(page, limit);
            List<Asset> assets = assetService.list(key);
            PageInfo<Asset> pageInfo = new PageInfo<>(assets);
            responseOBJ.setData(assets);
            responseOBJ.setCount(pageInfo.getTotal());
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @PostMapping("/update")
    public ResponseOBJ<Integer> update(@RequestBody Asset asset) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = assetService.update(asset);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }
}
